﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using twistmachinev2.Entity;
using twistmachinev2.Repository;

namespace twistmachinev2
{
    public partial class FrmRecipe : XtraForm
    {
        private SqliteRepository _repository;
        private List<Recipe> _recipes;
        private Recipe _currentRecipe;
        private bool _isEditing = false;
        private bool _isAdding = false;

        public FrmRecipe()
        {
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeForm()
        {
            try
            {
                _repository = new SqliteRepository();
                
                // 确保Recipe表存在
                _repository.CreateTableIfNotExists<Recipe>();
                
                // 初始化界面
                InitializeGrid();
                InitializeEvents();
                LoadRecipes();
                SetControlsEnabled(false);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeGrid()
        {
            // 配置GridView基本显示选项
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsView.ShowColumnHeaders = true;  // 显示列标题
            gridView1.OptionsView.ShowIndicator = true;      // 显示行号
            gridView1.OptionsView.ColumnAutoWidth = false;   // 使用手动设置的列宽
            gridView1.OptionsSelection.MultiSelect = false;
            gridView1.OptionsBehavior.ReadOnly = true;       // 设置为只读
          
        }

        private void InitializeEvents()
        {
            // 按钮事件
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnSave.Click += BtnSave_Click;
            btnCancel.Click += BtnCancel_Click;
            btnRefresh.Click += BtnRefresh_Click;
            
            // Grid事件
            gridView1.FocusedRowChanged += GridView1_FocusedRowChanged;
            
            // 窗体事件
            this.FormClosed += FrmRecipe_FormClosed;
        }

        private void FrmRecipe_FormClosed(object sender, FormClosedEventArgs e)
        {
            _repository?.Dispose();
        }

        private void LoadRecipes()
        {
            try
            {
                _recipes = _repository.GetList<Recipe>();
                
                // 强制刷新GridControl
                gridControl1.DataSource = null;
                gridControl1.RefreshDataSource();
                gridControl1.DataSource = _recipes;
                
                // 确保GridView正确显示
                gridView1.RefreshData();
                gridView1.LayoutChanged();
                gridControl1.Refresh();
                
                // 如果有数据，选中第一行
                if (_recipes != null && _recipes.Count > 0)
                {
                    gridView1.FocusedRowHandle = 0;
                }
                else
                {
                    // 即使没有数据也要确保列标题显示
                    gridView1.RefreshData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载配方数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                _currentRecipe = gridView1.GetFocusedRow() as Recipe;
                if (_currentRecipe != null && !_isEditing && !_isAdding)
                {
                    DisplayRecipe(_currentRecipe);
                }
            }
        }

        private void DisplayRecipe(Recipe recipe)
        {
            if (recipe == null) return;
            
            txtRecipeNo.Text = recipe.RecipeNo;
            txtRecipeName.Text = recipe.RecipeName;
            txtBeforeWorkLength.Value = recipe.BeforeWorkLength ?? 0;
            txtAfterWorkLength.Value = recipe.AfterWorkLength ?? 0;
            txtOpen1Width.Value = recipe.Open1Width ?? 0;
            txtTwistPitch.Value = recipe.TwistPitch ?? 0;
            txtOpen2Width.Value = recipe.Open2Width ?? 0;
            txtOuterDiameter.Value = recipe.OuterDiameter ?? 0;
            txtExpandCorrect.Value = recipe.ExpandCorrect ?? 0;
            txtPositiveNumber.Value = recipe.PositiveNumber ?? 0;
            txtNegativeNumber.Value = recipe.NegativeNumber ?? 0;
        }

        private void ClearForm()
        {
            txtRecipeNo.Text = string.Empty;
            txtRecipeName.Text = string.Empty;
            txtBeforeWorkLength.Value = 0;
            txtAfterWorkLength.Value = 0;
            txtOpen1Width.Value = 0;
            txtTwistPitch.Value = 0;
            txtOpen2Width.Value = 0;
            txtOuterDiameter.Value = 0;
            txtExpandCorrect.Value = 0;
            txtPositiveNumber.Value = 0;
            txtNegativeNumber.Value = 0;
        }

        private void SetControlsEnabled(bool enabled)
        {
            txtRecipeNo.Enabled = enabled;
            txtRecipeName.Enabled = enabled;
            txtBeforeWorkLength.Enabled = enabled;
            txtAfterWorkLength.Enabled = enabled;
            txtOpen1Width.Enabled = enabled;
            txtTwistPitch.Enabled = enabled;
            txtOpen2Width.Enabled = enabled;
            txtOuterDiameter.Enabled = enabled;
            txtExpandCorrect.Enabled = enabled;
            txtPositiveNumber.Enabled = enabled;
            txtNegativeNumber.Enabled = enabled;
            
            btnSave.Enabled = enabled;
            btnCancel.Enabled = enabled;
            
            btnAdd.Enabled = !enabled;
            btnEdit.Enabled = !enabled && _currentRecipe != null;
            btnDelete.Enabled = !enabled && _currentRecipe != null;
            btnRefresh.Enabled = !enabled;
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            _isAdding = true;
            _isEditing = false;
            _currentRecipe = null;
            
            ClearForm();
            SetControlsEnabled(true);
            txtRecipeNo.Focus();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (_currentRecipe == null)
            {
                XtraMessageBox.Show("请选择要编辑的配方", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            _isEditing = true;
            _isAdding = false;
            
            SetControlsEnabled(true);
            txtRecipeNo.Focus();
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (_currentRecipe == null)
            {
                XtraMessageBox.Show("请选择要删除的配方", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            if (XtraMessageBox.Show($"确定要删除配方 '{_currentRecipe.RecipeName}' 吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    _repository.DeleteById<Recipe>(_currentRecipe.Id);
                    XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadRecipes();
                    ClearForm();
                    _currentRecipe = null;
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"删除失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateInput())
                return;
            
            try
            {
                Recipe recipe = CreateRecipeFromForm();
                
                if (_isAdding)
                {
                    recipe.CreateTime = DateTime.Now;
                    recipe.UpdateTime = DateTime.Now;
                    _repository.Insert(recipe);
                    XtraMessageBox.Show("新增成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (_isEditing)
                {
                    recipe.Id = _currentRecipe.Id;
                    recipe.CreateTime = _currentRecipe.CreateTime;
                    recipe.UpdateTime = DateTime.Now;
                    _repository.Update(recipe);
                    XtraMessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
                LoadRecipes();
                ResetEditState();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            if (_currentRecipe != null)
            {
                DisplayRecipe(_currentRecipe);
            }
            else
            {
                ClearForm();
            }
            
            ResetEditState();
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadRecipes();
        }

        private void ResetEditState()
        {
            _isAdding = false;
            _isEditing = false;
            SetControlsEnabled(false);
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txtRecipeNo.Text))
            {
                XtraMessageBox.Show("请输入配方编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRecipeNo.Focus();
                return false;
            }
            
            if (string.IsNullOrWhiteSpace(txtRecipeName.Text))
            {
                XtraMessageBox.Show("请输入配方名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRecipeName.Focus();
                return false;
            }
            
            // 检查配方编号是否重复
            if (_isAdding || (_isEditing && _currentRecipe.RecipeNo != txtRecipeNo.Text))
            {
                var existingRecipe = _repository.GetList<Recipe>(r => r.RecipeNo == txtRecipeNo.Text).FirstOrDefault();
                if (existingRecipe != null)
                {
                    XtraMessageBox.Show("配方编号已存在，请使用其他编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtRecipeNo.Focus();
                    return false;
                }
            }
            
            return true;
        }

        private Recipe CreateRecipeFromForm()
        {
            return new Recipe
            {
                RecipeNo = txtRecipeNo.Text.Trim(),
                RecipeName = txtRecipeName.Text.Trim(),
                BeforeWorkLength = txtBeforeWorkLength.Value,
                AfterWorkLength = txtAfterWorkLength.Value,
                Open1Width = txtOpen1Width.Value,
                TwistPitch = txtTwistPitch.Value,
                Open2Width = txtOpen2Width.Value,
                OuterDiameter = txtOuterDiameter.Value,
                ExpandCorrect = txtExpandCorrect.Value,
                PositiveNumber = (long)txtPositiveNumber.Value,
                NegativeNumber = (long)txtNegativeNumber.Value
            };
        }


    }
}
